var app = getApp();
Page({
    data: {
        goodsList: {
            saveHidden: true,
            totalPrice: 0,
            allSelect: "",
            noSelect: false,
            list: [],
            to_pay_is_show: false
        },
        delBtnWidth: 120,  //删除按钮宽度单位（rpx）
        to_pay: false,
        to_pay_is_show: '',
        is_authorization: true,
        is_show: true,
        code: "获取验证码",
        avatarUrl: "../../images/tx.jpg"
    },
    onLoad: function (options) {
        this.initEleWidth();
    },
    onReady: function () {

    },
    onShow: function () {
        var that = this;
        that.init();
        // that.manual_login();
    },
    touchStart: function (e) {
        if (e.touches.length == 1) {
            this.setData({
                startX: e.touches[0].clientX
            });
        }
    },
    touchMove: function (e) {
        var that = this;
        var index = e.currentTarget.dataset.index;
        if (e.touches.length == 1) {
            var moveX = e.touches[0].clientX;
            var disX = this.data.startX - moveX;
            var delBtnWidth = this.data.delBtnWidth;
            var left = "";
            if (disX == 0 || disX < 0) {//如果移动距离小于等于0，container位置不变
                left = "margin-left:0px";
            } else if (disX > 0) {//移动距离大于0，container left值等于手指移动距离
                left = "margin-left:-" + disX + "px";
                if (disX >= delBtnWidth) {
                    left = "left:-" + delBtnWidth + "px";
                }
            }
            var list = this.data.goodsList.list;
            if (index != "" && index != null) {
                list[parseInt(index)].left = left;
                that.setData({
                    "goodsList.list": list
                })
            }
        }
    },
    touchEnd: function (e) {
        var that = this;
        var index = e.currentTarget.dataset.index;
        if (e.changedTouches.length == 1) {
            var endX = e.changedTouches[0].clientX;
            var disX = this.data.startX - endX;
            var delBtnWidth = this.data.delBtnWidth;
            //如果距离小于删除按钮的1/2，不显示删除按钮
            var left = disX > delBtnWidth / 2 ? "margin-left:-" + delBtnWidth + "px" : "margin-left:0px";
            var list = this.data.goodsList.list;
            if (index !== "" && index != null) {
                list[parseInt(index)].left = left;
                that.setData({
                    "goodsList.list": list
                })
            }
        }
    },
    getEleWidth: function (w) {
        var real = 0;
        try {
            var res = wx.getSystemInfoSync().windowWidth;
            var scale = (750 / 2) / (w / 2);  //以宽度750px设计稿做宽度的自适应
            real = Math.floor(res / scale);
            return real;
        } catch (e) {
            return false;
            // Do something when catch error
        }
    },
    initEleWidth: function () {
        var delBtnWidth = this.getEleWidth(this.data.delBtnWidth);
        this.setData({
            delBtnWidth: delBtnWidth
        });
    },//购物车列表
    cart_list: function (member_id) {
        var that = this;
        var params = {};
        params['member_id'] = member_id;
        wx.request({
            url: app.config() + 'cart/selects',
            data: params,
            header: {
                'content-type': 'application/json'
            },
            success: function (res) {
                if (res.data.status == 0) {
                    var tempArray = new Array();
                    var arr = new Array();
                    if (res.data.data.length) {
                        that.setData({
                            to_pay_is_show: true
                        })
                    } else {
                        that.setData({
                            to_pay_is_show: false
                        })
                    }
                    for (var i = 0; i < res.data.data.length; i++) {
                        var cart = res.data.data[i].cart;
                        var goods = res.data.data[i].goods;
                        cart['goods_name'] = goods.name;
                        cart['sales_money'] = goods.sales_money;
                        cart['mainUrl'] = goods.mainUrl;
                        cart['selected'] = cart.selected;
                        cart['goods_status'] = goods.status;
                        cart['index'] = cart.length;
                        tempArray.push(cart);
                        arr.push(cart.selected)
                    }
                    var flag = false;
                    // 1选中2非选中
                    if (!that.inArray(arr, '2')) {
                        flag = true;
                    }
                    if (that.inArray(arr, '1')) {
                        that.setData({
                            to_pay: true
                        })
                    } else {
                        that.setData({
                            to_pay: false
                        })
                    }
                    that.setData({
                        "goodsList.list": tempArray,
                        "goodsList.allSelect": flag
                    })
                    var currentAllSelect = that.data.goodsList.allSelect;
                    var index = that.data.goodsList.list.length;
                    that.setData({
                        cart_index: index
                    })
                    that.setGoodsList(that.totalPrice(), currentAllSelect, tempArray);
                }
            }
        })
    },//更新购物车
    cart_updates: function (params) {
        var that = this;
        var member_id = that.data.member_id;
        wx.showToast({
            title: '加载中……',
            icon: 'loading',
            duration: 50000
        })
        wx.request({
            url: app.config() + 'cart/updates',
            data: params,
            header: {
                'content-type': 'application/json'
            },
            success: function (res) {
                if (res.data.status == 0) {
                    wx.hideToast()
                    if (member_id) {
                        that.cart_list(member_id);
                    }
                } else {
                    wx.hideToast()
                }
            },
            fail: function () {
                wx.hideToast()
            }
        })
    },//购物车减少数量
    reduceBtnTap: function (e) {
        var that = this;
        var index = e.currentTarget.dataset.index;
        var currentAllSelect = that.data.goodsList.allSelect;
        var list = this.data.goodsList.list;
        var id = e.currentTarget.dataset.id;
        if (index !== "" && index != null) {
            if (list[parseInt(index)].goods_number > 1) {
                list[parseInt(index)].goods_number--;
                this.setGoodsList(this.totalPrice(), currentAllSelect, list);
            }
            var params = {};
            params['goods_number'] = list[parseInt(index)].goods_number;
            params['id'] = id;
            this.cart_updates(params);
        }
    },//购物车增加数量
    increaseBtnTap: function (e) {
        var that = this;
        var index = e.currentTarget.dataset.index;
        var currentAllSelect = that.data.goodsList.allSelect;

        var list = this.data.goodsList.list;
        var id = e.currentTarget.dataset.id;
        if (index !== "" && index != null) {
            list[parseInt(index)].goods_number++;
            this.setGoodsList(this.totalPrice(), currentAllSelect, list);
        }
        var params = {};
        params['goods_number'] = list[parseInt(index)].goods_number;
        params['id'] = id;
        this.cart_updates(params);
    },//选中某个商品
    selectTap: function (e) {
        var that = this;
        var index = e.currentTarget.dataset.index;
        var currentAllSelect = that.data.goodsList.allSelect;
        var list = this.data.goodsList.list;
        var id = e.currentTarget.dataset.id;
        var is_select = list[index].selected;//判断是否选中
        if (is_select == 1) {
            var is_select_args = 2;
        } else {
            var is_select_args = 1;
        }
        list[parseInt(index)].selected = is_select_args;
        this.setGoodsList(this.totalPrice(), currentAllSelect, list);
        var params = {};
        params['selected'] = is_select_args;
        params['id'] = id;
        this.cart_updates(params);
    },//全选商品
    selectAll: function () {
        var currentAllSelect = this.data.goodsList.allSelect;
        var list = this.data.goodsList.list;
        if (currentAllSelect) {
            for (var i = 0; i < list.length; i++) {
                list[i].selected = false;
                var params = {};
                params['selected'] = 2;
                params['id'] = list[i].id;
                this.cart_updates(params);
            }
        } else {
            for (var i = 0; i < list.length; i++) {
                list[i].selected = true;
                var params = {};
                params['selected'] = 1;
                params['id'] = list[i].id;
                this.cart_updates(params);
            }
        }
        this.setGoodsList(this.totalPrice(), !currentAllSelect, list);
    },//删除商品
    delItem: function (e) {
        var cart_id = e.target.dataset.id;
        var params = {};
        params['id'] = cart_id;
        params['status'] = 1;
        this.cart_updates(params)
    },
    setGoodsList: function (total, allSelect, list) {
        this.setData({
            goodsList: {
                totalPrice: total,
                allSelect: allSelect,
                list: list
            }
        });
    },//计算总价
    totalPrice: function () {
        var list = this.data.goodsList.list;
        var total = 0;
        for (var i = 0; i < list.length; i++) {
            var curItem = list[i];
            if (curItem.selected == 1) {
                total += parseFloat(curItem.sales_money) * curItem.goods_number;
            }
        }
        return total;
    },//去结算
    toPayOrder: function () {
        wx.showToast({
            title: '加载中……',
            icon: 'loading',
            duration: 50000
        });
        var that = this;
        var data = that.data.goodsList.list;
        var index = data.length;
        var params = {};
        var list = {};
        for (var i = 0; i < index; i++) {
            if (data[i].selected == 1) {
                var goods_status = data[i].goods_status;
                var id = data[i].id;
                list[i] = id;
                // status商品状态：0 -> 上架 ， 1 -> 下架 ， 2 -> 售罄',
                if (goods_status != 0) {
                    wx.showToast({
                        title: "购物车里有下架商品",
                        icon: "loading"
                    })
                    return;
                } else {
                    wx.hideToast()
                }
            }

        }
        params['cartIDs'] = list;
        // 将整合的参数存到本地，到下个页面取出来
        wx.setStorage({
            key: 'cartIDs',
            data: list,
            success: function () {
                wx.navigateTo({
                    url: '../settlement/settlement',
                })
            }
        })
    },//判断某个元素是否在数组中
    inArray: function (arr, obj) {
        var i = arr.length;
        while (i--) {
            if (arr[i] === obj) {
                return true;
            }
        }
        return false;
    },
    init: function () {
        var that = this;
        wx.getStorage({
            key: 'userInfo',
            success: function (res) {
                if (res.errMsg == "getStorage:ok") {
                    var nickName = res.data.nickName;
                    var avatarUrl = res.data.avatarUrl;
                    var open_id = res.data.open_id;
                    that.setData({
                        memberInfo: res.data,
                        loginAuthor: false,
                        nickName: nickName,
                        avatarUrl: avatarUrl,
                        perfect: true
                    })
                }
            },
            fail: function () {
                that.setData({
                    is_login: false
                })
            }
        })
        // 检验登陆状态
        wx.getStorage({
            key: 'memberInfo',
            success: function (res) {
                var data = res.data;
                var member_id = data.id;
                var open_id = data.open_id;
                that.cart_list(member_id)
                if (member_id && open_id) {
                    that.setData({
                        is_login: true,
                        member_id: member_id,
                        is_authorization: true,
                        open_id: open_id
                    })
                } else if (!member_id && open_id) {
                    that.setData({
                        is_login: false,
                        is_authorization: false,
                        open_id: open_id
                    })
                } else if (!member_id && !open_id) {
                    wx.switchTab({
                        url: "../../images/myPage/myPage"
                    })
                }
            }
        })
    },//获取验证码
    clickVerify: function () {
        var that = this;
        var phone_number = that.data.phone;
        if (phone_number) {
            if (!app.phone_number_reg(phone_number)) {
                wx.showToast({
                    title: '请输入正确的手机号',
                    icon: "loading"
                })
            } else {
                // 将获取验证码按钮隐藏60s，60s后再次显示
                that.setData({
                    is_show: !that.data.is_show   //false
                })
                settime(that);
                // 发送验证码
                var params = {};
                params['phone_number'] = phone_number;
                wx.request({
                    url: app.config() + "member/xiaoSendCode",
                    data: params,
                    header: {
                        'content-type': 'application/json'
                    },
                    success: function (res) {
                        // 操作太过于频繁tips
                        if (res.data.status == 4) {
                            wx.showToast({
                                title: '请稍后重试',
                                imagg: "../../images/warning.png"
                            })
                        }
                    }
                })
            }
        } else {
            wx.showToast({
                title: '请输入手机号',
                icon: "loading"
            })
        }
    },//手机号码
    member_phone: function (e) {
        var that = this;
        var phone = e.detail.value;
        that.setData({
            phone: phone
        })
    },//验证码
    verification_code: function (e) {
        var that = this;
        var code = e.detail.value;
        that.setData({
            code: code
        })
    },//提交登陆
    submit: function () {
        var that = this;
        var phone_number = that.data.phone;
        var code = that.data.code;
        var open_id = that.data.open_id;
        if (!phone_number) {
            return;
        }
        if (!app.phone_number_reg(phone_number)) {
            return;
        }
        if (!code) {
            wx.showToast({
                title: '请输入验证码',
                image: "../../images/warning.png"
            })
            return;
        }
        var params = {};
        params['phone_number'] = phone_number;
        params['verify_code'] = code;
        params['open_id'] = open_id;
        wx.request({
            url: app.config() + "member/xiaoLogANDReg",
            data: params,
            header: {
                'content-type': 'application/json'
            },
            success: function (res) {
                if (res.data.data.status == 0) {
                    var data = res.data.data;
                    wx.showToast({
                        title: '验证成功',
                        icon: 'success'
                    })
                    wx.setStorage({
                        key: 'memberInfo',
                        data: data,
                    })
                    that.setData({
                        is_authorization: true
                    })
                    that.init();
                } else {
                    wx.showToast({
                        title: res.data.message,
                        image: "../../images/warning.png"
                    })
                }
            }
        })
    }
})


var countdown = 60;
var settime = function (that) {
    if (countdown == 0) {
        that.setData({
            is_show: true,
            last_time: ""
        })
        countdown = 60;
        return;
    } else {
        that.setData({
            is_show: false,
            last_time: countdown
        })
        countdown--;
    }
    setTimeout(function () {
        settime(that)
    }, 1000)
}